package server

import (
	"common/database/config"
	"context"
	"errors"
	"golang.org/x/crypto/bcrypt"
	"user_srv/internal/models/dao"
	pb "user_srv/proto"
)

type Server struct {
	pb.UnimplementedUserServer
}

func (c *Server) Register(ctx context.Context, request *pb.RegisterRequest) (*pb.RegisterResponse, error) {
	password, _ := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
	user := dao.User{
		Tel:      request.Tel,
		Password: string(password),
	}
	err := config.DB.Create(&user).Error
	if err != nil {
		return nil, errors.New("注册失败")
	}
	return &pb.RegisterResponse{Id: int64(user.ID)}, nil
}

func (c *Server) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
	var user *dao.User
	config.DB.Where("tel=?", request.Tel).Find(&user).Limit(1)
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(request.Password))
	if err != nil {
		return nil, errors.New("密码错误")
	}
	return &pb.LoginResponse{Id: int64(user.ID)}, nil
}
